import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Box,
  Typography,
  Paper,
  Chip,
  Button,
  Divider,
  IconButton,
  Breadcrumbs,
  Link,
  Grid,
  Card,
  CardContent,
  CardActionArea,
  CircularProgress,
  Pagination,
} from '@mui/material';
import {
  Edit as EditIcon,
  Delete as DeleteIcon,
  Add as AddIcon,
  ArrowBack as ArrowBackIcon,
  Folder as FolderIcon,
  LocalOffer as TagIcon,
  Visibility as VisibilityIcon,
} from '@mui/icons-material';
import axios from 'axios';

const CategoryDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [category, setCategory] = useState(null);
  const [knowledges, setKnowledges] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  
  const pageSize = 9;

  useEffect(() => {
    const fetchCategory = async () => {
      setLoading(true);
      try {
        const response = await axios.get(`/api/category/${id}`);
        setCategory(response.data);
        
        // 获取该分类下的知识条目
        const knowledgeResponse = await axios.get(`/api/knowledge?category_id=${id}&page=${page}&page_size=${pageSize}`);
        setKnowledges(knowledgeResponse.data.data);
        setTotalPages(Math.ceil(knowledgeResponse.data.total / pageSize));
        
        setError(null);
      } catch (err) {
        console.error('获取分类详情失败:', err);
        setError('获取分类详情失败，请稍后重试');
      } finally {
        setLoading(false);
      }
    };

    fetchCategory();
  }, [id, page]);

  const handleEdit = () => {
    navigate(`/category/edit/${id}`);
  };

  const handleDelete = async () => {
    if (!window.confirm('确定要删除这个分类吗？这将同时删除该分类下的所有子分类。')) return;

    try {
      await axios.delete(`/api/category/${id}`);
      navigate('/categories');
    } catch (err) {
      console.error('删除分类失败:', err);
      alert('删除失败，请稍后重试');
    }
  };

  const handleBack = () => {
    navigate(-1);
  };

  const handleAddKnowledge = () => {
    // 预设分类ID
    navigate(`/knowledge/new?category_id=${id}`);
  };

  const handlePageChange = (event, value) => {
    setPage(value);
  };

  const handleKnowledgeClick = (knowledgeId) => {
    navigate(`/knowledge/${knowledgeId}`);
  };

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50vh' }}>
        <CircularProgress />
      </Box>
    );
  }

  if (error) {
    return (
      <Box sx={{ textAlign: 'center', py: 4 }}>
        <Typography variant="h6" color="error">
          {error}
        </Typography>
        <Button variant="contained" onClick={handleBack} sx={{ mt: 2 }}>
          返回
        </Button>
      </Box>
    );
  }

  if (!category) return null;

  return (
    <Box sx={{ flexGrow: 1 }}>
      <Box sx={{ mb: 2, display: 'flex', alignItems: 'center' }}>
        <IconButton onClick={handleBack} sx={{ mr: 1 }}>
          <ArrowBackIcon />
        </IconButton>
        <Breadcrumbs aria-label="breadcrumb">
          <Link color="inherit" onClick={() => navigate('/')} sx={{ cursor: 'pointer' }}>
            首页
          </Link>
          {category.parent && (
            <Link 
              color="inherit" 
              onClick={() => navigate(`/category/${category.parent.id}`)} 
              sx={{ cursor: 'pointer' }}
            >
              {category.parent.name}
            </Link>
          )}
          <Typography color="text.primary">{category.name}</Typography>
        </Breadcrumbs>
      </Box>

      <Paper elevation={1} sx={{ p: 3, mb: 3 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 2 }}>
          <Box sx={{ display: 'flex', alignItems: 'center' }}>
            <FolderIcon sx={{ mr: 1, color: 'primary.main' }} />
            <Typography variant="h4" component="h1" gutterBottom>
              {category.name}
            </Typography>
          </Box>
          <Box>
            <IconButton onClick={handleEdit} color="primary">
              <EditIcon />
            </IconButton>
            <IconButton onClick={handleDelete} color="error">
              <DeleteIcon />
            </IconButton>
          </Box>
        </Box>

        {category.description && (
          <Typography variant="body1" paragraph>
            {category.description}
          </Typography>
        )}

        {category.children && category.children.length > 0 && (
          <Box sx={{ mt: 3 }}>
            <Typography variant="h6" gutterBottom>
              子分类
            </Typography>
            <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
              {category.children.map((child) => (
                <Chip
                  key={child.id}
                  icon={<FolderIcon />}
                  label={child.name}
                  onClick={() => navigate(`/category/${child.id}`)}
                  variant="outlined"
                  sx={{ mb: 1 }}
                />
              ))}
            </Box>
            <Divider sx={{ my: 2 }} />
          </Box>
        )}

        <Box sx={{ mt: 3 }}>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
            <Typography variant="h5">
              知识条目
            </Typography>
            <Button
              variant="contained"
              startIcon={<AddIcon />}
              onClick={handleAddKnowledge}
            >
              添加知识
            </Button>
          </Box>

          {knowledges.length > 0 ? (
            <>
              <Grid container spacing={3}>
                {knowledges.map((knowledge) => (
                  <Grid item xs={12} sm={6} md={4} key={knowledge.id}>
                    <Card sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
                      <CardActionArea onClick={() => handleKnowledgeClick(knowledge.id)}>
                        <CardContent sx={{ flexGrow: 1 }}>
                          <Typography gutterBottom variant="h6" component="div" noWrap>
                            {knowledge.title}
                          </Typography>
                          <Typography variant="body2" color="text.secondary" sx={{ mb: 2, height: '3em', overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>
                            {knowledge.content.replace(/<[^>]*>/g, '')}
                          </Typography>
                          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mt: 1 }}>
                            <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
                              {knowledge.tags && knowledge.tags.slice(0, 2).map((tag) => (
                                <Chip
                                  key={tag.id}
                                  size="small"
                                  icon={<TagIcon fontSize="small" />}
                                  label={tag.name}
                                  variant="outlined"
                                />
                              ))}
                            </Box>
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                              <VisibilityIcon fontSize="small" color="action" />
                              <Typography variant="caption" color="text.secondary">
                                {knowledge.views}
                              </Typography>
                            </Box>
                          </Box>
                          <Box sx={{ mt: 1 }}>
                            {Array(knowledge.importance).fill().map((_, i) => (
                              <span key={i} role="img" aria-label="star">★</span>
                            ))}
                          </Box>
                        </CardContent>
                      </CardActionArea>
                    </Card>
                  </Grid>
                ))}
              </Grid>

              {totalPages > 1 && (
                <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
                  <Pagination 
                    count={totalPages} 
                    page={page} 
                    onChange={handlePageChange} 
                    color="primary" 
                  />
                </Box>
              )}
            </>
          ) : (
            <Box sx={{ textAlign: 'center', py: 4 }}>
              <Typography variant="body1" color="text.secondary">
                该分类下暂无知识条目
              </Typography>
              <Button
                variant="contained"
                startIcon={<AddIcon />}
                onClick={handleAddKnowledge}
                sx={{ mt: 2 }}
              >
                添加第一个知识条目
              </Button>
            </Box>
          )}
        </Box>
      </Paper>
    </Box>
  );
};

export default CategoryDetail;